import time
from flask import current_app
from extensions import celery, db, stock_redis
from ..models import Stockdetail
# from ..constants import (CELERY_EXCHANGE_SALE_STOCK_QUEUE)
from celery_redis_sentinel import register
from hashlib import md5
from ..utils.decorators import with_session

register()


__all__ = ['stock_unregist_task']


@celery.context_task(bind=True, default_retry_relay=10, max_retires=5)
@with_session
def stock_unregist_task(self, sku_id, source_orders, log_data=None, to_sync=True):
    """
        取消销售库存登记任务
        :param sku_id:
        :param source_orders:
        :param log_data:
        :param to_sync:
    """
    try:

        print('testtestestestesteestestes')

        if isinstance(source_orders, str):
            source_orders = [source_orders]
        if isinstance(sku_id, (int, str)):
            sku_id = [sku_id]
        md5_orders = list()
        source_orders = list(set(source_orders))
        source_orders.sort()
        md5_order_id = md5(','.join(source_orders).encode()).hexdigest()
        current_app.logger.info(">>>> gen md5_order_id {} from {} <<<<".format(md5_order_id, ','.join(source_orders)))
        md5_orders.append(md5_order_id)
        for order in source_orders:
            md5_order_id = md5(order.encode()).hexdigest()
            md5_orders.append(md5_order_id)
            current_app.logger.info("!!! gen md5_order_id {} from {}".format(md5_order_id, order))
        # records = db.session.query(StockRegist).with_lockmode('update').filter(StockRegist.order_id.in_(md5_orders),
        #                                                                        StockRegist.sku_id.in_(
        #                                                                            sku_id),
        #                                                                        StockRegist.is_deleted == 0).all()
        db.session.commit()
    except Exception as ex:
        current_app.logger.error(ex, exc_info=1)
        raise self.retry(exc=ex, countdown=10)
